package com.sky.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.exception.BaseException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {

        Employee employee = employeeMapper.getByUsername(employeeLoginDTO.getUsername());
        //todo employee 是null 需要报错

        if(employee==null){
            //日志要真实详细
            log.info("用户不存在");
            //报错信息可以模糊
            throw new BaseException("用户不存在或者密码不正确");

        }

        //dto中明文密码加密成密文密码
        MD5 md5=new MD5();
        String hexPassword = md5.digestHex(employeeLoginDTO.getPassword());

        //employee.getPassword() 是数据库中存储密文
        //md5特性，明文一致则密文一致，密文一致说明明文也一致
        if(!employee.getPassword().equals(hexPassword)){
            log.info("密码不正确");
            //密码不正确，报错
            throw new BaseException("用户不存在或者密码不正确");
        }
        //能到这里说明账号和密码都正确
        return employee;
    }

    @Override
    public void add(EmployeeDTO employeeDTO) {
        //dto没有password dto->pojo
        Employee employee=new Employee();
        //属性对拷
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setPassword("123456");
        employee.setStatus(0);
        employeeMapper.add(employee);
    }

    @Override
    public Employee findById(long id) {
        return employeeMapper.findById(id);
    }

    @Override
    public PageResult getPage(int page, int pageSize) {
        PageResult pageResult=new PageResult();
        //接受count值
        long count=employeeMapper.count();
        pageResult.setTotal(count);
        //查询符合条件的员工列表
        List<Employee> employeeList=employeeMapper.getList();
        //stream流
        List<Employee> list= employeeList.stream()
                .skip((page - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
        pageResult.setRecords(list);

        return pageResult;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        employeeMapper.update(employeeDTO);
    }

    @Override
    public void status(Employee employee) {
        employeeMapper.status(employee);
    }
}
